package main

import (
	"context"
	"fmt"
	"git.oschina.net/fanbuchi/redpack/constant"
	"git.oschina.net/fanbuchi/redpack/database"
	_ "git.oschina.net/fanbuchi/redpack/docs"
	"git.oschina.net/fanbuchi/redpack/env"
	"git.oschina.net/fanbuchi/redpack/routers"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	serverlessplus "github.com/serverlessplus/go"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"github.com/tencentyun/scf-go-lib/cloudfunction"
	"net"
	"net/http"
	"strconv"
)




// @title 小红包
// @version 1.0
// @description 小红包API
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email chengdukm@gmail.com

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host service-4pvwx5e4-1251434793.gz.apigw.tencentcs.com/test
// @host-local 192.168.1.4:8090
// @BasePath /red_pack
const (
	 port = 8090
	 projectName  = constant.ProjectName
)

var handler *serverlessplus.Handler

func init(){
	if env.GetFuncMode() {
		r := routers.Setup()

		r.GET(projectName+"/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

		l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", serverlessplus.Host, port))
		if err != nil {
			fmt.Printf("failed to listen on port %d: %v\n", port, err)
			// panic to force the runtime to restart
			panic(err)
		}
		go http.Serve(l, r)

		// setup handler
		types := make(map[string]struct{})
		types["image/png"] = struct{}{}
		handler = serverlessplus.NewHandler(port).WithBinaryMIMETypes(types)

	}
}

func entry(ctx context.Context, req *serverlessplus.APIGatewayRequest) (*serverlessplus.APIGatewayResponse, error) {
	return handler.Handle(ctx, req)
}

func main() {
	if !env.GetFuncMode() {
		//本地服务部署
		r := routers.Setup()
		r.GET(constant.ProjectName+"/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
		defer database.Master().Close()
		// Listen and Server in 0.0.0.0:8080
		r.Run("192.168.1.4:"+strconv.Itoa(port))
	}else{
		// 函数服务部署
		defer database.Master().Close()
		cloudfunction.Start(entry)
	}
}